<template>
  <div>
    <!-- 省级下拉框 -->
    <el-select
      v-if="type === 'prov'"
      v-model="selectedRegion"
      @change="handleRegionChange"
      filterable
      clearable
      placeholder="请选择省份"
    >
      <el-option
        v-for="item in provinceList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>

    <!-- 省市区级联选择 -->
    <el-cascader
      v-else
      v-model="selectedRegion"
      :options="regionList"
      :props="{ expandTrigger: 'hover' }"
      @change="handleRegionChange"
      filterable
      clearable
      placeholder="请选择省市区"
    />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { cleanRegionTree } from "@/utils/cleanRegionTree";

export default {
  name: "RegionCascader",
  props: {
    value: {},
    type: {
      type: String,
      default: "all",
      validator: (val) => ["all", "prov"].includes(val),
    },
  },
  computed: {
    ...mapGetters(["regionList"]),
    selectedRegion: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
    provinceList() {
      // 提取省级选项
      const rawList = JSON.parse(JSON.stringify(this.regionList || []));
      const cleanedList = cleanRegionTree(rawList);
      return cleanedList;
    },
  },
  methods: {
    handleRegionChange(value) {
      const selectedValue = value;
      let regionLabels = [];

      if (this.type === "prov") {
        // 单层结构处理
        const node = this.provinceList.find((item) => item.value === value);
        if (node) {
          regionLabels.push(node.label);
        }
      } else {
        // 多层结构处理
        let currentLevel = this.regionList;
        for (let id of value) {
          const node = currentLevel.find((item) => item.value === id);
          if (!node) break;
          regionLabels.push(node.label);
          currentLevel = node.children || [];
        }
      }

      this.$emit("change", {
        value: selectedValue,
        labels: regionLabels,
      });
    },
  },
  created() {
    this.$store.dispatch("mall/loadRegionList").then(() => {
      // console.log("regionList", this.regionList);
    });
  },
};
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>